//
//  PaymentModel.m
//  huashiedu
//
//  Created by oceans on 2018/9/10.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "PaymentModel.h"
#import "PaymentView.h"
#import "HttpRequest.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
#import "TipManager.h"
#import "LoginViewController.h"

@interface PaymentModel () <PaymentViewDelegate>

@property (strong, nonatomic) NSDictionary *info;
@property (strong, nonatomic) NSDictionary *payResponse;
@property (strong, nonatomic) UIView *coverView;
@property (strong, nonatomic) PaymentView *payView;
@end

static PaymentModel *shared;

@implementation PaymentModel

+ (instancetype)shared {
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        shared = [[self alloc] init];
    });
    return shared;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        shared = [super allocWithZone:zone];
    });
    return shared;
}

- (id)copyWithZone:(NSZone*)zone {
    return shared;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

/*id = 1;
 name = "\U4e66\U6cd5\U7ed8\U753b\U4e00\U65e5\U4fee";
 price = "259.00";*/
- (void)showPaymentView:(NSDictionary *)info {
    _info = info;
    [[UIApplication sharedApplication].keyWindow addSubview:self.coverView];
    _coverView.hidden = NO;
    NSAttributedString *qian = [[NSAttributedString alloc] initWithString:@"¥" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:10.0], NSForegroundColorAttributeName: [UIColor colorWithRed:1 green:0 blue:54/255.0 alpha:1.0]}];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[info objectForKey:@"price"] attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:19.0], NSForegroundColorAttributeName: [UIColor colorWithRed:1 green:0 blue:54/255.0 alpha:1.0]}];
    [string insertAttributedString:qian atIndex:0];
    _payView.priceLabel.attributedText = string;
}

- (UIView *)coverView {
    if (!_coverView) {
        _coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _coverView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        [_coverView addSubview:self.payView];
    }
    return _coverView;
}

- (PaymentView *)payView {
    if (!_payView) {
        _payView = [[NSBundle mainBundle] loadNibNamed:@"PaymentView" owner:self options:nil].firstObject;
        _payView.delegate = self;
        _payView.center = CGPointMake(ScreenWidth * 0.5, ScreenHeight * 0.5);
    }
    return _payView;
}

- (void)closePaymentView {
    _coverView.hidden = YES;
    [_coverView removeFromSuperview];
    if (_webCon) {
        [_webCon finishPay];
        self.webCon = nil;
    }
}

- (void)confirmPayment:(NSDictionary *)info {
    
    if ([UserModel shared].hasLogin == NO) {
        
        _coverView.hidden = YES;
        [_coverView removeFromSuperview];
        UINavigationController *navi = [LoginViewController loginViewController];
        [self.webCon presentViewController:navi animated:YES completion:nil];
        return;
    }
    
    __weak typeof(self) weakself = self;
    if ([[info objectForKey:@"pay"] integerValue] == 0) {
        //微信
        [HttpRequest postURL:kpayment paras:@{@"course_id": [NSNumber numberWithInt:[[_info objectForKey:@"id"] intValue]], @"paymode": @"wechat"} showProgress:YES successful:^(id  _Nullable result) {
            NSLog(@"%@", result);
            if ([WXApi isWXAppInstalled]) {
                NSDictionary *dic = result[@"data"][@"wechat"];
                PayReq *request = [[PayReq alloc] init];
                request.partnerId = [dic objectForKey:@"partnerid"];
                request.prepayId = [dic objectForKey:@"prepayid"];
                request.package = [dic objectForKey:@"package"];
                request.nonceStr = [dic objectForKey:@"noncestr"];
                request.timeStamp = [[dic objectForKey:@"timestamp"] intValue];
                request.sign = [dic objectForKey:@"sign"];
                weakself.isPaying = YES;
                [WXApi sendReq:request];
            }else {
                [TipManager showTip:@"未安装微信"];
            }
        } failed:nil];
    }else {
        //支付宝
        [HttpRequest postURL:kpayment paras:@{@"course_id": [NSNumber numberWithInt:[[_info objectForKey:@"id"] intValue]], @"paymode": @"alipay"} showProgress:YES successful:^(id  _Nullable result) {
            NSLog(@"%@", result);
            NSString *alipay = result[@"data"][@"alipay"];
            weakself.isPaying = YES;
            [[AlipaySDK defaultService] payOrder:alipay fromScheme:@"huashiedu" callback:^(NSDictionary *resultDic) {
                NSLog(@"%@", resultDic);
            }];
        } failed:nil];
    }
}

- (void)payFinished {
    self.isPaying = NO;
    if (_webCon) {
        [_webCon finishPay];
        self.webCon = nil;
    }
    [self closePaymentView];
}

- (void)payFailed {
    self.isPaying = NO;
}

@end
